import { nextTick } from "../utils";

let queue = [];
let has = {}; // 做列表  维护存放了哪些watcher

let pending = false;

function flushSchedulerQueue() {
  for (let i = 0; i < queue.length; i++) {
    queue[i].run();
  }
  queue = [];
  has = {};
  pending = false;
}

export function queueWatcher(watcher) {
  //  当前执行栈中代码执行完毕，会清空微任务， 再清空宏任务 这里希望尽快更新
  const id = watcher.id;
  if (!has[id]) {
    queue.push(watcher);
    has[id] = true;
    // 开启一此更新操作 批处理 防抖
    if (!pending) {
      // setTimeout(flushSchedulerQueue, 0);
      // setTimeout 宏任务
      nextTick(flushSchedulerQueue);
      pending = true;
    }
  }
}
